package com.aihuishou.monitor.model;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class DefaultTransaction implements Transaction {
    public DefaultTransaction() {
        this.timestamp = System.currentTimeMillis();
        this.durationStart = System.nanoTime();
    }

    /**
     * 一级分类
     */
    private String type;

    /**
     * 二级分类
     */
    private String name;

    /**
     * 创建的时间戳，ms
     */
    private long timestamp;

    /**
     * 状态  0:成功  其他:失败
     */
    private String status;

    /**
     * 是否完成
     */
    private boolean completed;

    /**
     * 附加信息
     */
    private String attribute;

    /**
     * 开始时间, 纳秒
     */
    private long durationStart;

    /**
     * 响应时间 微妙
     */
    private long durationInMicro = -1;

    /**
     * 子消息；暂时不使用，留着扩展
     */
    private List<Message> childList;

    @Override
    public void complete() {
        if (!isCompleted()) {
            if (durationInMicro == -1) {
                durationInMicro = (System.nanoTime() - durationStart) / 1000L;
            }
            setCompleted(true);
        }
    }

    public DefaultTransaction copy() {
        DefaultTransaction copyT = new DefaultTransaction();
        copyT.setType(this.getType());
        copyT.setName(this.getName());
        copyT.setTimestamp(this.getTimestamp());
        copyT.setStatus(this.getStatus());
        copyT.setCompleted(this.isCompleted());
        copyT.setAttribute(this.getAttribute());
        copyT.setDurationStart(this.getDurationStart());
        copyT.setDurationInMicro(this.getDurationInMicro());
        return copyT;
    }

    @Override
    public void addChild(Message t) {
        if (childList != null) {
            childList.add(t);
        } else {
            childList = new ArrayList<>();
            childList.add(t);
        }
    }
}
